package tool.zyk.echoserver;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * author: zyk
 * datetime: 2024/1/26 22:01
 * describe:
 */
@Slf4j
public class EchoServerClient {
    public static void main(String[] args) throws InterruptedException {

        Channel channel = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info("client in:{}", buf.toString(Charset.defaultCharset()));

                            }
                        });
                    }
                })
                .connect("127.0.0.1", 8084)
                .sync()
                .channel();

        channel.closeFuture().addListener(future -> {
        });

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入:");
            String input = scanner.nextLine();
            if ("q".equals(input)) {
                break;
            }
            channel.writeAndFlush(input);
        }


    }
}
